package com.gitee.limaozhi.socket.lesson03.example1;

import com.gitee.limaozhi.socket.lesson02.example3.LineDelimiterDecoder;
import com.gitee.limaozhi.util.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.List;

/**
 * @author hzlimaozhi
 * @date 2019/08/26 12:48
 */
public class Client {

    public static void client(String name) throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(8000));

        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();
        ClientLogicHandler logicHandler = new ClientLogicHandler();
        LineDelimiterDecoder delimiterDecoder = new LineDelimiterDecoder();

        byte[] buffer = new byte[1024];
        boolean stop = false;
        while (!stop) {
            String request = logicHandler.getRequest();
            if (request == null) {
                break;
            }
            System.out.println("客户端" + name + "：" + request);

            // 发送给服务器
            byte[] requestBytes = LineDelimiterEncoder.encode(request);
            outputStream.write(requestBytes);

            // 读取服务器的响应
            while (true) {
                int count = inputStream.read(buffer);
                if (count == -1) {
                    stop = true;
                    break;
                }
                List<String> responses = delimiterDecoder.decode(Utils.copy(buffer, 0, count));
                if (responses.size() > 0) {
                    for (String response : responses) {
                        System.out.println("服务器" + name + "：" + response);
                    }
                    System.out.println();
                    break;
                }
            }
        }

        socket.close();
        System.out.println("客户端" + name + "：关闭");
    }

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < 5; i++) {
            String name = String.valueOf(i+1);
            new Thread(() -> {
                try {
                    Client.client(name);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
//        Client.client("");
    }

}
